<!-- components/SearchSelect.vue -->
<template>
  <view>
    <!-- 输入框 -->
    <uni-easyinput
      v-model="inputValue"
      :placeholder="placeholder"
      @input="handleInput"
      @focus="openDropdown"
    />
    
    <!-- 下拉弹窗 -->
    <uni-popup ref="popup" type="bottom" :mask-click="true" @maskClick="closeDropdown">
      <view class="popup-content">
        <uni-list v-if="filteredOptions.length > 0">
          <uni-list-item
            v-for="(item, index) in filteredOptions"
            :key="index"
            :title="item.label"
            @click="selectItem(item)"
          />
        </uni-list>
        <view v-else class="empty-tip">
          {{ emptyText }}
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  modelValue: { type: [String, Number], default: '' },  // v-model 绑定值
  options: { type: Array, default: () => [] },         // 选项列表，格式: [{label, value}]
  placeholder: { type: String, default: '请搜索选择' },  // 占位文本
  emptyText: { type: String, default: '无匹配数据' },   // 空数据提示
  filterable: { type: Boolean, default: true },        // 是否启用模糊搜索
});

const emit = defineEmits(['update:modelValue', 'search']);

const inputValue = ref('');
const popup = ref(null);
const showDropdown = ref(false);

// 过滤后的选项
const filteredOptions = computed(() => {
  if (!props.filterable || !inputValue.value) return props.options;
  return props.options.filter(item =>
    item.label.toLowerCase().includes(inputValue.value.toLowerCase())
  );
});

// 输入事件（可加入防抖）
const handleInput = (val) => {
  inputValue.value = val;
  emit('search', val); // 可触发远程搜索
};

// 打开下拉
const openDropdown = () => {
  showDropdown.value = true;
  popup.value?.open();
};

// 关闭下拉
const closeDropdown = () => {
  showDropdown.value = false;
  popup.value?.close();
};

// 选择项
const selectItem = (item) => {
  emit('update:modelValue', item.value);
  inputValue.value = item.label;
  closeDropdown();
};

// 监听外部 modelValue 变化（如重置表单）
watch(() => props.modelValue, (newVal) => {
  const selectedItem = props.options.find(item => item.value === newVal);
  inputValue.value = selectedItem?.label || '';
});
</script>

<style scoped>
.popup-content {
  background: #fff;
  padding: 10px;
  max-height: 50vh;
  overflow-y: auto;
}
.empty-tip {
  padding: 15px;
  text-align: center;
  color: #999;
}
</style>